﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web;
using System.Windows.Forms;
using SinaWeiboPlugin;
using SinaWeiboPlugin.Properties;
using Slippor.Douban.Radio.Assist;

namespace SinaWeiboUserControl
{
    public partial class FortuneTellerControl : UserControl
    {
        private readonly Settings _settings = SinaWeiboConfig.SettingManager.Settings as Settings;
        private readonly Dictionary<Fortune, ListViewItem> _fortuneDics = new Dictionary<Fortune, ListViewItem>();

        private TweetBuilder _tweetBuilder;
        internal TweetBuilder Builder
        {
            set { _tweetBuilder = value; }
        }

        public FortuneTellerControl()
        {
            InitializeComponent();
            if (_settings.FortunedDay > new DateTime(1991, 1, 1))
            {
                labelStatus.Text = String.Format("上一轮占卜 {0:yyyy-MM-dd HH:mm} ", FortuneTeller.LastFortuneDate);
                if (_settings.FortuneOnceDay && FortuneTeller.FortunedToday)
                {
                    labelStatus.Text += "，今日占卜已经结束。";
                }
            }
            else
            {
                labelStatus.Text = String.Format("还未进行过占卜。", _settings.FortunedDay);
            }
        }

        public void RefreshFortuneList()
        {
            listViewHistory.Items.Clear();
            _fortuneDics.Clear();
            foreach (var fortune in FortuneTeller.AvailabelFortunes)
            {
                var lvi = new ListViewItem(fortune.Question);
                if (!String.IsNullOrEmpty(fortune.Question))
                {
                    lvi.Text = fortune.Question;
                    lvi.ToolTipText = fortune.Question;
                }
                if (fortune.Answer != null)
                {
                    String subItem = String.Empty;
                    if (fortune.Answer.Album != null)
                    {
                        subItem = String.Format(String.Format("{0}({1})", fortune.Answer.Title, fortune.Answer.Album.ArtistString));
                    }
                    else
                    {
                        subItem = String.Format(String.Format("{0}", fortune.Answer.Title));
                    }
                    lvi.SubItems.Add(subItem);
                }
                else
                {
                    lvi.SubItems.Add("-");
                }
                listViewHistory.Items.Add(lvi);
                _fortuneDics[fortune] = lvi;
                lvi.Tag = fortune;
            }
        }

        public void Update(Fortune fortune)
        {
            if (_fortuneDics.ContainsKey(fortune))
            {
                foreach (ListViewItem item in listViewHistory.SelectedItems)
                {
                    item.Selected = false;
                }
                _fortuneDics[fortune].Selected = true;
                SetFortuneDes(fortune);
            }
        }

        private void listViewHistory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listViewHistory.SelectedItems != null && listViewHistory.SelectedItems.Count == 1)
            {
                var fortune = listViewHistory.SelectedItems[0].Tag as Fortune;
                SetFortuneDes(fortune);
            }
        }

        private void SetFortuneDes(Fortune fortune)
        {
            if (fortune != null)
            {
                labelQuestion.Text = fortune.Question;
                if (fortune.Answer != null)
                {
                    if (fortune.Answer.Album != null)
                    {
                        labelAnswer.Text = String.Format(String.Format("{0}({1})", fortune.Answer.Title, fortune.Answer.Album.ArtistString));
                    }
                    else
                    {
                        labelAnswer.Text = String.Format(String.Format("{0}", fortune.Answer.Title));
                    }
                    buttonSend.Tag = fortune;
                    buttonSend.Enabled = true;
                }
                else
                {
                    labelAnswer.Text = "-";
                    buttonSend.Enabled = false;
                    buttonSend.Tag = null;
                }
            }
            else
            {
                labelQuestion.Text = "-";
                labelAnswer.Text = "-";
                buttonSend.Enabled = false;
                buttonSend.Tag = null;
            }
        }

        private void buttonReset_Click(object sender, EventArgs e)
        {
            foreach (var item in FortuneTeller.AvailabelFortunes)
            {
                item.Answer = null;
                item.InUse = false;
            }
            RefreshFortuneList();
            SetFortuneDes(null);
        }

        public void SendFortune(Fortune fortune)
        {
            using (BackgroundWorker sendWorker = new BackgroundWorker())
            {
                buttonSend.Text = "发送中...";
                buttonSend.Enabled = false;
                _tweetBuilder.Message = FortuneTeller.BuildTweet(fortune);
                sendWorker.DoWork += (senderD, eD) =>
                {
                    eD.Result = _tweetBuilder.Upload();
                };
                sendWorker.RunWorkerCompleted += (senderC, eC) =>
                {
                    if (eC.Error == null && (bool)eC.Result)
                    {
                        buttonSend.Text = "发送成功";
                    }
                    else
                    {
                        buttonSend.Text = "发送失败";
                        if (_settings.ErrorAlert)
                        {
                            if (eC.Error != null)
                            {
                                MessageBox.Show(eC.Error.Message);
                            }
                        }
                    }
                    buttonSend.Enabled = true;
                };
                sendWorker.RunWorkerAsync();
            }
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            if (buttonSend.Tag != null)
            {
                Fortune fortune = buttonSend.Tag as Fortune;
                if (fortune != null)
                {
                    SendFortune(fortune);
                }
            }
        }

        private static void linkLabelBrowser_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            RadioUtility.Browse(String.Format("http://t.sina.com.cn/k/{0}", HttpUtility.UrlEncode("电台占卜")));
        }
    }
}
